import axios from 'axios';
import jsonBig from 'json-bigint';
const contentType = 'application/json;charset=UTF-8'
//修
// var base ='/api';
var base='http://125.46.5.250:9736'
const JSONbigToString = jsonBig({ storeAsString: true });
const instance = axios.create({
	timeout: 2000,
	baseURL: base,
	headers: {
		'Content-Type': contentType,
	},
	transformResponse: [
		function (data) {
			try {
				return JSONbigToString.parse(data);
			} catch (err) {
				return data;
			}

		}
	]
})
// axios的全局配置
instance.defaults.headers.post = {
	'Content-Type': 'application/json'
}
instance.defaults.headers.common = {
	'Auth-Type': 'company-web',
	'X-Requested-With': 'XMLHttpRequest',
}
instance.defaults.headers['Access-Control-Allow-Origin'] = "*";
instance.defaults.headers['Access-Control-Allow-Methods'] = "GET,PUT,POST,DELETE,OPTIONS";

// 添加请求拦截器(post只能接受字符串类型数据)
instance.interceptors.request.use(
	config => {
		const token = localStorage.getItem('token');
		if (!token && config.url == '/user/login') {
			return config;
		} else {
			config.headers['token'] = token;
			return config;
		}
	},
	error => {
		return Promise.reject(error)
	}
)
const errorHandle = (status, other) => {
	switch (status) {
		case 400:
            console.log('信息校验失败');
			break
		case 401:
			// @ts-nocheck
            console.log('认证失败');
			break
		case 403:
            console.log('token校验失败');
			break
		case 404:
            console.log('请求的资源不存在');
			break
		default:
            console.log(other);
			break
	}
}

// 添加响应拦截器
instance.interceptors.response.use(
	// 响应包含以下信息data,status,statusText,headers,config
	res => {
		if (res.data && res.data.code !== 0 && !(res.data instanceof Blob)) {
            // console.log(res.data.message || '服务器出错!');
		}
		// 请求通用处理
		return res.data
	},
	err => {
		// console.log(err);
		const { response } = err
		if (response) {
			errorHandle(response.status, response.data)
			return Promise.reject(response)
		}
        // console.log('请求失败');
		return true
	}
)

export default instance;